// 防抖函数
export function debounce(fn: Function, delay: number = 500) {
  let timer: any = null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

// 对象映射成label value
export function mapToLabelValue(obj: any) {
  return Object.entries(obj).map(([value, label]) => ({
    label,
    value
  }))
}

// 对象有值则赋值,没有值则删除
export function updateParams(params, prop, value) {
  if (value === 0 || value) {
    params[prop] = value
  } else {
    Reflect.deleteProperty(params, prop)
  }
  return params
}

// 字符串格式的日期转时间戳
export function timeToTimestamp(time) {
  const [hours, minutes] = time.split(':')
  const date = new Date()
  date.setHours(parseInt(hours, 10))
  date.setMinutes(parseInt(minutes, 10))
  date.setSeconds(0)
  date.setMilliseconds(0)
  return date.getTime()
}

// 时间戳转字符串格式的日期
export function timestampToTime(timestamp) {
  const date = new Date(timestamp)
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 数据库时间格式转字符串格式的日期
export function dbTimeToTime(dbDateTime) {
  const utcDateTime = new Date(dbDateTime)
  const formattedDateTime = utcDateTime
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
    .replace(/\//g, '-')

  return formattedDateTime
}
